﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Ex8.BASE64Format
{
    class BASE64Format
    {
        private const string originalFileName = "../../Resources/Notepad.exe";
        private const string resultFileName = "notepad.txt";

        private const string encodedFileName = resultFileName;
        private const string decodedFileName = "notepad.exe";

        static void Main(string[] args)
        {
            Encode(originalFileName,resultFileName);
            Decode(encodedFileName,decodedFileName);
        }

        private static void Decode(string encodedFile, string decodedFile)
        {
            //Read Base64 notepad.txt
            string byte64File;
            using (StreamReader sr = new StreamReader(encodedFile))
            {
                byte64File = sr.ReadToEnd();
            }
            //Create notepad.exe from the Base64 string.
            using (FileStream fs = new FileStream(decodedFile, FileMode.Create))
            {
                byte[] bytes = Convert.FromBase64String(byte64File);
                fs.Write(bytes, 0, bytes.Length);
            }
        }

        private static void Encode(string originalFile,string resultFile)
        {
            //Read Notepad.exe
            byte[] buffer;
            using (FileStream fs = new FileStream(originalFile , FileMode.Open))
            {
                buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
            }

            //Write notepad.txt in Base64
            using (StreamWriter sw = new StreamWriter(resultFile))
            {
                string encodedText = Convert.ToBase64String(buffer);
                for (int i = 0; i < encodedText.Length; i++)
                {
                    if (i % 40 == 0 && i != 0)
                    {
                        sw.WriteLine();
                    }
                    sw.Write(encodedText[i]);
                }
            }
        }
    }
}